package com.lyh.hkcloud.module.m1300092;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import androidx.annotation.RequiresApi;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.HomeActivity;
import com.lyh.hkcloud.base.BaseActivity;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.common.ActivityUtil;
import com.lyh.hkcloud.module.m1300092.adapter.ListViewAdapter;
import com.lyh.hkcloud.module.m1300092.service.Service;
import com.lyh.hkcloud.util.base.*;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: huangbincheng
 * @program: hkCloud
 * @description: 网罩领用登记
 * @company—date: 利元数据 2023-03-09 16:28
 **/
public class IndexActivity extends BaseActivity implements View.OnClickListener, ListViewAdapter.DeleteCallback {

    private ImageView goBack;
    private Button btSave;
    private Button btResetting;
    private EditText etMesh;
    private Service service;
    private EditText etArea;
    private ListView lvMesh;
    private List<Map<String, Object>> dataMap = new ArrayList<>();
    private ListViewAdapter listViewAdapter;
    private Integer receiverFocusEvent = 0;
    private EditText etReceiver;
    private TextView tvUser;
    private TextView tvDept;

    /**
     * 网罩编码
     */
    List<Map<String,Object>> meshCodeList = new ArrayList<>();
    List<String> codeList = new ArrayList<>();
    /**
     * 提交网罩信息
     */
    Map<String, Object> meshMap = new HashMap<>();


    @Override
    protected Activity getActivity() {
        return this;
    }

    @Override
    protected int getSubmitResId() {
        return R.id.bt_save;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_1300092;
    }

    @Override
    protected int getClearResId() {
        return R.id.bt_resetting;
    }

    @Override
    protected void onBeginInit() {
        service = new Service(IndexActivity.this);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView() {
        goBack = findViewById(R.id.go_back);
        btSave = findViewById(R.id.bt_save);
        lvMesh = findViewById(R.id.lv_mesh);
        etMesh = findViewById(R.id.et_mesh);
        btResetting = findViewById(R.id.bt_resetting);
        etArea= findViewById(R.id.et_area);
        etReceiver = findViewById(R.id.et_receiver);
        tvUser = findViewById(R.id.tv_user);
        tvDept = findViewById(R.id.tv_dept);
        //获得焦点，并关闭软盘
        etMesh.setShowSoftInputOnFocus(false);
        goBack.setOnClickListener(this);
        etMesh.setOnClickListener(this);
        etArea.setOnClickListener(this);
        etReceiver.setOnClickListener(this);
        getSupportActionBar().hide();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        listViewAdapter = new ListViewAdapter(this, dataMap, IndexActivity.this);
        listViewAdapter.setDeleteCallback(this);
        lvMesh.setAdapter(listViewAdapter);
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (ActivityUtil.isShouldHideKeyboard(v, ev)) {
                ActivityUtil.hideKeyboard(v.getWindowToken(), this, etMesh);
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void initEvent() {
        //回车事件，查询网罩信息
        etMesh.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //查询网罩
                JSONObject jsonObject = new JSONObject();
                try {
                    //网罩编号，有些数据格式是：A007 2022-11-1，需要去掉空格后面的日期
                    String[] mesh=etMesh.getText().toString().replace(BusinessConstants.SCAN_AREA,"").split(" ");
                    String meshInfo=mesh.length>0?mesh[0]:"";
                    if (codeList.indexOf(mesh) != -1) {
                        Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                    }else if(StringUtils.isNotEmpty(meshInfo)){
                        jsonObject.put("mesCoverCode", meshInfo);
                        queryAssets(jsonObject);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                etMesh.setText("");
                return true;
            }
        });

        //网罩编码 获取焦点事件
        etMesh.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.SCAN_MESH_2.equals(String.valueOf(etMesh.getText()))) {
                        etMesh.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {

                    if (etMesh.getText() == null || "".equals(etMesh.getText().toString())) {
                        etMesh.setText(BusinessConstants.SCAN_MESH_2);
                    }
                }

                receiverFocusEvent = 0;


            }
        });

        //区域编码
        etArea.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (BusinessConstants.SCAN_AREA_1.equals(String.valueOf(etArea.getText()))) {
                        etArea.setText("");
                    }
                    receiverFocusEvent = 1;
                } else {
                    if (etArea.getText() == null || "".equals(String.valueOf(etArea.getText()))) {
                        etArea.setText(BusinessConstants.SCAN_AREA_1);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });

        //区域编码回车事件
        etArea.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                etMesh.requestFocus();
                return true;
            }
        });

        //工号回车事件
        etReceiver.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                etArea.requestFocus();
                return true;
            }
        });

        etReceiver.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.v("借用人",etReceiver.getText().toString());
                Log.v("hasFocus",String.valueOf(hasFocus));
                if(hasFocus){
                    if (BusinessConstants.SCAN_PSN_CODE.equals(etReceiver.getText().toString())) {
                        etReceiver.setText("");
                    }
                    receiverFocusEvent = 1;
                }else{
                    if ( etReceiver.getText() == null || "".equals(etReceiver.getText().toString())) {
                        etReceiver.setText(BusinessConstants.SCAN_PSN_CODE);
                    }else{
                        JSONObject jsonObject = new JSONObject();

                        try {
                            jsonObject.put("psncode", etReceiver.getText());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        queryPersonnelInformation(jsonObject);
                    }
                    receiverFocusEvent = 0;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        registerReceiver(receiver, Filter());
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterReceiver(receiver);
    }

    private static IntentFilter Filter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BusinessConstants.ACTION);
        return intentFilter;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onClear(View... ignores) {
        super.onClear(ignores);
        dataMap.clear();
        meshCodeList.clear();
        codeList.clear();
        updateAssetList();
        etReceiver.clearFocus();
        etArea.clearFocus();
        etMesh.clearFocus();
        Log.v("clear**", "清空**");
    }

    @Override
    protected void onSubmit() {

        if (BusinessConstants.SCAN_PSN_CODE.equals(etReceiver.getText()) || StringUtils.isEmpty(String.valueOf(etReceiver.getText()))) {
            Toast.makeText(IndexActivity.this, "使用人工号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("根据工号自动带出".equals(tvUser.getText()) || StringUtils.isEmpty(String.valueOf(tvUser.getText()))) {
            Toast.makeText(IndexActivity.this, "使用人名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        Editable area = etArea.getText();
        if (StringUtils.isEmpty(String.valueOf(area)) || BusinessConstants.SCAN_AREA_1.equals(area.toString())) {
            Toast.makeText(IndexActivity.this, "区域编码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (codeList.size() == 0) {
            Toast.makeText(IndexActivity.this, "请扫描添加网罩信息", Toast.LENGTH_SHORT).show();
            return;
        }
        //禁用提交按钮
        btSave.setEnabled(false);

        //组装参数
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            jsonObject.put("usedPsnCode", etReceiver.getText());
            jsonObject.put("usedPsnName", tvUser.getText());
            //jsonObject.put("userDeptName", SaveData.getString(this, "userDept"));
            jsonObject.put("areaCode", area);
            jsonObject.put("usedDeptName", tvDept.getText());
            jsonObject.put("meshCoverList", JsonUtil.toJSONArray(meshCodeList));

            Log.v("jsonObject网罩信息提交", jsonObject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        showProgressDialog("提示", "提交中...");

        service.post(jsonObject, HttpUrlComstants.ADD_FA_MESH_COVER_RECORD, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Toast.makeText(IndexActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                LoadingUtils.getInstance(IndexActivity.this).hide();
//                onClear();
                onClick(goBack);
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                LoadingUtils.getInstance(IndexActivity.this).hide();
                btSave.setEnabled(true);
            }
        });
        hideProgressDialog();
    }


    /**
     * 扫描 接收者
     *
     * @author: zhongfan
     * @Date 2022/2/15 21:00
     **/
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            etMesh.clearFocus();
            String msg =intent.getStringExtra(BusinessConstants.TAG);
            Log.i(BusinessConstants.TAG, msg);

            JSONObject jsonObject = new JSONObject();

            try {
                jsonObject.put("mesCoverCode", msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //添加接收人
            if (receiverFocusEvent == 1) {
                etMesh.setText(msg);
                /*查询网罩信息*/
                //queryMeshInformation(jsonObject);
                return;
            }

            if (codeList.indexOf(msg) != -1) {
                Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                return;
            }

            showProgressDialog("提示", "查询中...");
            /*查询网罩*/
            //queryMeshInformation(jsonObject);

            hideProgressDialog();
        }
    };


    /**
     * 查询网罩信息
     */
    private void queryAssets(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_MESH, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                JSONArray data = response.optJSONArray("data");
                JSONObject jsonObject3 = null;
                try {
                    if(data.length()==0){
                        Toast.makeText(IndexActivity.this, "该网罩编码不存在", Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    JSONObject meshInfo =data.getJSONObject(0);
                    if (null ==meshInfo) {
                        Toast.makeText(IndexActivity.this, "该网罩编码不存在", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    JSONArray meshArray=meshInfo.getJSONArray("result");
                    if(meshArray.length()==0){
                        Toast.makeText(IndexActivity.this, "该网罩编码不存在", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    jsonObject3 =meshArray.getJSONObject(0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject3 == null) {
                    Toast.makeText(IndexActivity.this, "该网罩编码不存在", Toast.LENGTH_SHORT).show();
                    return;
                }

                Map<String, Object> map = new HashMap<>();
                map.put("mesCoverCode", jsonObject3.optString("mes_cover_code") == null ? "" : jsonObject3.optString("mes_cover_code"));
                map.put("maName", jsonObject3.optString("ma_name") == null ? "" : jsonObject3.optString("ma_name"));
                map.put("mesCoverCode", jsonObject3.optString("mes_cover_code") == null ? "" : jsonObject3.optString("mes_cover_code"));
                map.put("manageDeptName", jsonObject3.optString("manage_dept_name") == null ? "" : jsonObject3.optString("manage_dept_name"));
                map.put("meshCoverType", jsonObject3.optString("mesh_cover_type") == null ? "" : jsonObject3.optString("mesh_cover_type"));
                String statusName=jsonObject3.optString("status_name");
                if("已报废".equals(statusName)){
                    Toast.makeText(IndexActivity.this, "该网罩已报废", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (codeList.indexOf(map.get("mesCoverCode")) == -1) {
                    dataMap.add(map);
                }else{
                    Toast.makeText(IndexActivity.this, "请不要重复扫描", Toast.LENGTH_SHORT).show();
                    return;
                }
                meshCodeList.add(map);
                codeList.add(jsonObject3.optString("mes_cover_code"));

                //通知ListView更改数据源
                updateAssetList();
            }

        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                Toast.makeText(IndexActivity.this, "查询网罩信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateAssetList() {
        //通知ListView更改数据源
        if (listViewAdapter != null) {
            listViewAdapter.notifyDataSetChanged();
        } else {
            listViewAdapter = new ListViewAdapter(IndexActivity.this, dataMap, IndexActivity.this);
            lvMesh.setAdapter(listViewAdapter);
        }
        lvMesh.setSelection(dataMap.size() - 1);//设置显示列表的最后一项
    }

    /**
     * 通过网罩编号，查询网罩信息
     *
     * @param jsonObject
     * @return void
     * @author: 黄斌成
     * @Date 2022/11/1 17:47
     **/
    public void queryMeshInformation(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_MESH, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                JSONArray data = response.optJSONArray("data");
                JSONObject jsonObject3 = null;
                try {
                    if(data.length()==0){
                        Toast.makeText(IndexActivity.this, "查询网罩信息为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    JSONArray meshInfo =data.getJSONArray(0);
                    if (meshInfo.length() == 0) {
                        Toast.makeText(IndexActivity.this, "查询网罩信息为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    jsonObject3 =meshInfo.getJSONObject(0);
                    Log.v("jsonObj333333:", jsonObject3.toString());

                    //使用人代码
                    meshMap.put("mesCoverCode", jsonObject3.get("mes_cover_code") == null ? "" : jsonObject3.optString("mes_cover_code"));
                    //使用人名称
                    meshMap.put("maName", jsonObject3.get("ma_name") == null ? "" : jsonObject3.optString("ma_name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void deletePosition(int saveposition) {
        Log.v("saveposition:", String.valueOf(saveposition));
        dataMap.remove(saveposition);
        meshCodeList.remove(saveposition);
        codeList.remove(saveposition);
        listViewAdapter.setData(dataMap);
        listViewAdapter.notifyDataSetInvalidated();
    }

    private ProgressDialog progressDialog;

    /**
     * 提示加载
     */
    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(IndexActivity.this, title, message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }

        progressDialog.show();

    }

    /**
     * 隐藏提示加载
     */
    public void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.go_back:
                Intent intent = new Intent(IndexActivity.this, HomeActivity.class);
                IndexActivity.this.startActivity(intent);
                break;
            case R.id.et_mesh:
                break;
        }
    }

    /**
     * 通过人员id，查询人员信息
     *
     * @param jsonObject
     * @return void
     * @author: huangbincheng
     * @Date 2023/3/9 17:47
     **/
    public void queryPersonnelInformation(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_PERSONNEL_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                JSONArray data = response.optJSONArray("data");
                JSONObject jsonObject3 = null;
                try {
                    JSONObject jsonObject2 = new JSONObject(data.get(0).toString());
                    JSONArray facardinfo = jsonObject2.optJSONArray("psninfo");
                    jsonObject3 = new JSONObject(facardinfo.get(0).toString());
                    Log.v("通过人员id，查询人员信息返回参数:", jsonObject3.toString());

                    if (jsonObject3 == null) {
                        Toast.makeText(IndexActivity.this, "获取领用人信息为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Map<String, Object> assetsMap = new HashMap<>();
                    //使用人id
                    assetsMap.put("psnid",jsonObject3.getString("psnid"));
                    //使用人代码
                    assetsMap.put("psncode",jsonObject3.getString("psncode"));
                    //使用人名称
                    assetsMap.put("psnname",jsonObject3.getString("psnname"));
                    tvUser.setText(jsonObject3.getString("psnname"));
                    tvDept.setText(jsonObject3.getString("deptname"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                ToastUtils.makeText(IndexActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

}

